<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区 -->
    <el-card class="box-card">
      <el-alert title="我警告你，小心一点！！！" type="warning" show-icon></el-alert>
      <el-row>
        <el-col>
          <span>
            选择商品分类：
            <el-cascader
              v-model="cateId"
              :options="cateList"
              :props="cateProps"
              @change="handleChange"
              clearable
            ></el-cascader>
          </span>
        </el-col>
      </el-row>
      <!-- 分类展示区 -->
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="静态参数" name="many">
          <el-button type="primary" :disabled="isdisabled" @click="showAddDialogVisible">添加参数</el-button>
          <!-- 表单区 -->
          <el-table :data="manyData" border style="width: 100%" stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  v-for="( item,index ) in scope.row.attr_vals"
                  :key="index"
                  closable
                  @close="removeTag(scope.row,item)"
                >{{item}}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column prop="attr_name" label="动态参数"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  @click="showEditDialogVisible(scope.row)"
                >编辑</el-button>
                <el-button type="success" icon="el-icon-delete">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="动态参数" name="only">
          <el-button type="primary" :disabled="isdisabled" @click="showAddDialogVisible">添加属性</el-button>
          <el-table :data="onlyData" border style="width: 100%" stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  v-for="( item,index ) in scope.row.attr_vals"
                  :key="index"
                  closable
                  @close="removeTag(scope.row,item)"
                >{{item}}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column prop="attr_name" label="静态属性"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  @click="showEditDialogVisible(scope.row)"
                >编辑</el-button>
                <el-button type="success" icon="el-icon-delete">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加分类参数弹框 -->
    <el-dialog
      :title="'添加' + ParamsText"
      :visible.sync="AddDialogVisible"
      width="30%"
      @close="resetForm"
    >
      <!-- 表单区 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
        <el-form-item :label="ParamsText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="AddDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑分类参数弹框 -->
    <el-dialog
      :title="'编辑' + ParamsText"
      :visible.sync="editDialogVisible"
      width="30%"
      @close="resetEditForm"
    >
      <!-- 表单区 -->
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px">
        <el-form-item :label="ParamsText" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      cateList: [],
      cateProps: {
        expandTrigger: 'hover',
        label: 'cat_name',
        value: 'cat_id',
        children: 'children'
      },
      cateId: [],
      activeName: 'many',
      manyData: [],
      onlyData: [],
      AddDialogVisible: false,
      addForm: {
        attr_name: ''
      },
      addFormRules: {
        attr_name: [{ required: true, message: '请输入活动名称', trigger: 'blur' }]
      },
      editDialogVisible: false,
      editForm: {
        attr_name: '',
        attr_id: 0
      },
      editFormRules: {
        attr_name: [{ required: true, message: '请输入活动名称', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    async getCateList() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.cateList = res.data
    },

    handleChange(value) {
      if (value.length !== 3) {
        this.cateId = []
        this.onlyData = []
        this.manyData = []
        return
      }

      this.getParamsData()
      // console.log(value)
    },
    handleClick() {
      if (this.paramsId === '') {
        return
      }
      // console.log(this.activeName)
      this.getParamsData()
    },

    async getParamsData() {
      const { data: res } = await this.$http.get(`categories/${this.paramsId}/attributes`, {
        params: { sel: this.activeName }
      })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)

      // 处理数据
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        item.inputVisible = false
        item.inputValue = ''
      })

      if (this.activeName === 'many') {
        this.manyData = res.data
      } else {
        this.onlyData = res.data
      }
    },

    resetForm() {
      this.$refs.addFormRef.resetFields()
    },
    resetEditForm() {
      this.$refs.editFormRef.resetFields()
    },
    showAddDialogVisible() {
      this.AddDialogVisible = true
    },
    async addParams() {
      const { data: res } = await this.$http.post(`categories/${this.paramsId}/attributes`, {
        attr_name: this.addForm.attr_name,
        attr_sel: this.activeName
      })
      if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      this.getParamsData()
      this.AddDialogVisible = false
    },
    async editParams() {
      const { data: res } = await this.$http.put(`categories/${this.paramsId}/attributes/${this.editForm.attr_id}`, {
        attr_name: this.editForm.attr_name,
        attr_sel: this.activeName
      })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      this.getParamsData()
      this.editDialogVisible = false
    },
    showEditDialogVisible(params) {
      this.editForm.attr_name = params.attr_name
      this.editForm.attr_id = params.attr_id
      this.editDialogVisible = true
    },
    async handleInputConfirm(row) {
      const str = row.inputValue.trim()
      if (str.length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return
      }
      row.attr_vals.push(str)
      const val = row.attr_vals.join(' ')
      const { data: res } = await this.$http.put(`categories/${this.paramsId}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        attr_vals: val
      })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)

      row.inputVisible = false
      row.inputValue = ''
    },
    showInput(row) {
      row.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    async removeTag(row, name) {
      const newVals = row.attr_vals.filter(item => {
        return item !== name
      })
      // console.log(newVals)
      row.attr_vals = newVals
      const val = newVals.join(' ')
      const { data: res } = await this.$http.put(`categories/${this.paramsId}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        attr_vals: val
      })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
    }
  },

  computed: {
    paramsId() {
      if (this.cateId.length === 3) {
        return this.cateId[2]
      } else {
        return ''
      }
    },

    isdisabled() {
      if (this.cateId.length !== 3) {
        return true
      } else {
        return false
      }
    },

    ParamsText() {
      if (this.activeName === 'many') {
        return '动态参数'
      } else {
        return '静态属性'
      }
    }
  }
}
</script>

<style lang="less" scoped>
.el-row {
  margin-top: 15px;
}
.el-tag {
  margin: 0 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
